<script setup>
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { View, ChatRound, Star, WarnTriangleFilled, StarFilled } from '@element-plus/icons-vue'
import PostListItemImage from '@/components/PostListItemImage.vue'
import { formatTime } from '@/utils/transIUtils'
import LikeLineIcon from '@/components/svgComponents/LikeLineIcon.vue'
import LikeIcon from '@/components/svgComponents/LikeIcon.vue'

import warning from '/imgs/commonIcons/warning.svg'
import ReportDialog from '@/components/commonUI/ReportDialog.vue'
import { useOptimisticUpdate } from '@/composables/useOptimisticUpdate'
import { postAddCollection, postCancelCollection } from '@/axios/api/posts'
import { get } from '@/axios/utils/request'
import { useGlobalStore } from '@/stores/globalStore'

const globalStore = useGlobalStore()
const props = defineProps({
  data: Object,
})

const emit = defineEmits(['hidePanel', 'refreshCollection'])

const route = useRoute()
const router = useRouter()

const { updatePostDetail } = useOptimisticUpdate()

const handleClick = () => {
  // const path = route.path.replace(/\/post.*/, '')
  router.push(`/home/post/${props.data.id}`)
  // router.push(`/topicExplore/post/${props.data.id}`)
  // router.push(`/home/post/${props.data.id}`)

  emit('hidePanel')
}


const addCollection = () => {
  // 乐观更新数据
  // updatePostDetail(props.data.id, (oldData) => ({
  //   ...oldData,
  //   isCollection: true,
  //   collectionCount: oldData.collectionCount + 1,
  // }))

  // 发送API请求
  postAddCollection({ id: props.data.id, uid: props.data.uid }).finally(() => {
    // 刷新数据
    emit('refreshCollection')
  })
}

const cancelCollection = () => {
  // 乐观更新数据
  // updatePostDetail(props.data.id, (oldData) => ({
  //   ...oldData,
  //   isCollection: false,
  //   collectionCount: oldData.collectionCount - 1,
  // }))

  // 发送API请求
  postCancelCollection({ id: props.data.id, uid: props.data.uid }).finally(() => {
    // 刷新数据
    emit('refreshCollection')
  })
}

//关注帖子
const handleFollow = async () => {
  try {
    await get('/post/fabulous/thumb', { id: props.data.id })
    ElMessage.success('关注成功')
    emit('refreshCollection')
    globalStore.setRefreshollowPost(!globalStore.refreshollowPost)
  } finally {
    // followLoading.value = false
  }
}
//取消关注帖子
const handleUnfollow = async () => {
  try {
    await get('/post/fabulous/cancel', { id: props.data.id })
    ElMessage.success('已取消关注')
    emit('refreshCollection')
    globalStore.setRefreshollowPost(!globalStore.refreshollowPost)
  } finally {
    // followLoading.value = false
  }
}

const formatNumber = (num) => {
  if (num > 9999) {
    return '9999+'
    // return (num / 10000).toFixed(1) + 'w'
  }
  return num
}

const parseMedia = (media) => {
  if (!media) return null
  // 如果是数组或对象，直接返回
  if (Array.isArray(media) || typeof media === 'object') return media
  // 如果是字符串，尝试解析
  try {
    // 先判断是不是以 [ 或 { 开头，才尝试 parse
    if (typeof media === 'string' && (media.trim().startsWith('[') || media.trim().startsWith('{'))) {
      return JSON.parse(media)
    }
    // 否则直接返回原字符串
    return media
  } catch (e) {
    // 解析失败，直接返回原字符串
    return media
  }
}

const tagColorList = ['primary', 'success', 'warning', 'danger', 'info', 'success', 'warning']
function getDiscussTagColorById(id) {
  if (!id) return tagColorList[0]
  let hash = 0
  const str = String(id)
  for (let i = 0; i < str.length; i++) hash = (hash * 31 + str.charCodeAt(i)) % 100000
  return tagColorList[hash % tagColorList.length]
}

// 举报相关
const showReportDialog = ref(false)
const reportInfo = ref({
  type: 'post',
  id: props.data?.id,
  title: props.data?.title,
  content: props.data?.content,
})

// 处理举报成功
const handleReportSuccess = () => {
  showReportDialog.value = false
  ElMessage.success('举报已提交，我们会尽快处理')
}

const handleTopicClick = (item) => {
  router.push(`/topic/${item.topicId}`)
}
const handleDiscussClick = (item) => {
  router.push(`/topic/${item.topicId}/discuss/${item.discussId}`)
}
const handleUserClick = (item) => {
  router.push(`/user/${item.userInfo.uid}`)
}
</script>

<template>
  <div @click="handleClick"
    class="hot-post-card group flex justify-between items-stretch cursor-pointer p-6 gap-6 w-full border-b border-gray-100 bg-gradient-to-br from-[#fafdff] to-[#f3f7fa] rounded-2xl shadow-sm hover:shadow-xl transition-all duration-200 relative overflow-hidden">
    <div class="min-w-0 flex-1 flex flex-col justify-between">
      <div>
        <div class="flex items-center">
          <el-avatar :size="46" :src="data.userInfo?.avatar" class="flex-shrink-0 shadow border border-blue-100" @click.stop="handleTopicClick(data)"/>
          <div class="items-center-left">
            <span class="text-base text-blue-900 font-semibold ml-3" @click.stop="handleTopicClick(data)">{{ data.topicName }}</span>
            <div class="items-center-left-info">
              <span class="text-xs text-gray-400 whitespace-nowrap"  @click.stop="handleUserClick(data)">{{ data.userInfo?.username }}</span>
              <span class="text-xs text-gray-400 whitespace-nowrap">&nbsp;&nbsp;{{ formatTime(data.createTime) }}</span>
            </div>
          </div>
          <el-tag v-if="data.discussTitle" :type="getDiscussTagColorById(data.id)" size="small"
            class="ml-3 font-medium px-3 py-1 text-sm" @click.stop="handleDiscussClick(data)">{{ data.discussTitle }}</el-tag>
        </div>
        <div class="font-bold text-lg  leading-snug line-clamp-2 hover:text-blue-600 text-blue-700 transition">{{
          data.title }}
          <span v-if="data.postTop > 0"
            class="bg-[#2e5592] rounded-full px-2 py-1 text-xs text-[#fff]  h-fit whitespace-nowrap ml-2">置顶</span>

        </div>
        <div class="text-[15px] text-gray-700 line-clamp-3 leading-relaxed" v-html="data.content.trim()"></div>
      </div>
      <div class="flex items-center gap-8 text-sm text-gray-500 border-t border-dashed border-gray-200 pt-2 mt-2">
        <div class="flex items-center gap-1 min-w-[60px]">
          <el-icon>
            <View />
          </el-icon>
          <span>{{ formatNumber(data.readCount || 0) }}</span>
        </div>
        <div class="flex items-center gap-1 min-w-[60px]" @click.stop.prevent="data.isCollection ? cancelCollection() : addCollection()" >
          <!-- <el-icon class="text-red-400"><Star /></el-icon> -->
          <LikeIcon v-if="data?.isCollection" class="w-4 like-animation" color="red" />
          <LikeLineIcon v-else class="w-4 like-animation" color="gray"  />
          <span>{{ formatNumber(data.collectionCount || 0) }}</span>
        </div>
        <div class="flex items-center gap-1 min-w-[60px]">
          <el-icon>
            <ChatRound />
          </el-icon>
          <span>{{ formatNumber(data.commentCount || 0) }}</span>
        </div>

        <!-- handleFollow  handleUnfollow  -->
        <div class="flex items-center gap-1 min-w-[60px]" @click.stop.prevent="data.isFabulous ? handleUnfollow() : handleFollow()">
          
          <!-- 需要后端一起调 -->
          <el-icon size="17" v-if="data?.isFabulous" color="#ff9b19"><StarFilled class="like-animation" /></el-icon>
          <el-icon v-else> 
            <Star />
          </el-icon>
          <span>{{ formatNumber(data.fabulousCount || 0) }}</span>
        </div>
        <div class="flex items-center gap-1 min-w-[60px]">
          <el-icon @click.stop="showReportDialog = true">
            <img :src="warning" alt="" />
          </el-icon>
        </div>
        <div class="flex gap-2 flex-wrap ml-auto">
          <el-tag v-for="tag in data.tags" :key="tag" size="small"
            class="!text-xs font-medium border-none bg-blue-50 text-blue-600 px-2" type="info" effect="plain">
            {{ tag }}
          </el-tag>
        </div>
      </div>
    </div>
    <div
      class="flex-shrink-0 flex items-center justify-center w-[120px] h-[120px] rounded-xl overflow-hidden bg-gray-100 border border-gray-200 ml-4">
      <PostListItemImage :type="data.type" :media="parseMedia(data.media)" class="object-cover w-full h-full" />
    </div>
    <div
      class="absolute inset-0 pointer-events-none rounded-2xl group-hover:ring-2 group-hover:ring-blue-200 transition">
    </div>
  </div>
  <ReportDialog v-model="showReportDialog" :report-info="reportInfo" :type="1" @success="handleReportSuccess" />
</template>

<style scoped lang="scss">
@keyframes likeScale {
  0% {
    transform: scale(0.5);
  }

  50% {
    transform: scale(1.3);
  }

  100% {
    transform: scale(1);
  }
}
.like-animation {
  animation: likeScale 0.3s ease;
}
.hot-post-card {
  max-width: 900px;
  margin: 0 auto 24px auto;
  box-sizing: border-box;

  .items-center-left {
    display: flex;
    flex-direction: column;

    .items-center-left-info {
      display: flex;
      margin-left: 0.75rem;
    }
  }

  @media (min-width: 1200px) {
    max-width: 1200px;
    // padding: 32px 38px 16px 38px;
    padding: 12px 18px 6px 18px;
    gap: 32px;
  }

  @media (max-width: 600px) {
    padding: 12px 6px;
    gap: 8px;
    border-radius: 10px;
  }
}
</style>
